<template>
	<view class="app-layout" @tap="handlePageTap">
		<!-- 顶部导航栏 -->
		<view class="topbar" @tap.stop="">
			<view class="topbar-left">
				<image class="logo" src="/static/logo_2.0.jpg"></image>
				<text class="brand">旭荣网盾(GDCS)</text>
			</view>
			<view class="topbar-center">
				<text class="page-title">智能问答</text>
			</view>
			<view class="topbar-right">
					<image class="icon" src="/static/Notice_0.png" @click="toggleNotification"></image>
					<image class="avatar" :src="currentAvatar" @click="toggleDropdown" />
			</view>
		</view>

		<view class="content">
			<!-- 悬浮菜单 -->
		<view class="dropdown-menu" v-if="showDropdown" @tap.stop="">
			<view class="dropdown-content">
					<view class="user-info">
											<image class="avatar lg" :src="currentAvatar" />
											<view class="user-meta">
												<text class="user-name">{{ user_name }}</text>
												<text class="user-role">{{ user_role }}</text>
											</view>
										</view>
					<view class="avatar-selector">
						<text class="selector-title">选择头像</text>
						<view class="avatar-grid">
							<image 
								v-for="(avatar, index) in avatarList" 
								:key="index"
								:src="avatar" 
								class="avatar-option"
								:class="{ active: currentAvatar === avatar }"
								@click="selectAvatar(avatar)"
							/>
						</view>
					</view>
					<view class="menu">
					<view class="menu-item" @click="navigateTo('history'); showDropdown = false">
							<image class="menu-icon" src="/static/lishi_chat.png"></image>
							<text>历史对话</text>
						</view>
						<view class="menu-item" @click="navigateTo('users'); showDropdown = false">
							<image class="menu-icon" src="/static/users.png"></image>
							<text>用户管理</text>
						</view>
						<view class="menu-item" @click="navigateTo('settings'); showDropdown = false">
							<image class="menu-icon" src="/static/xitongshezhi.png"></image>
							<text>系统设置</text>
						</view>
					<view class="menu-item logout-item" @click="logout(); showDropdown = false">
						<image class="logout-icon" src="/static/tuichudenglu.png"></image>
						<text>退出登录</text>
					</view>
				</view>
				</view>
			</view>



			<!-- 右侧主区域 -->
			<view class="main">
				<!-- 聊天区 -->
				<view class="main-inner">

					<!-- 聊天区域 -->
				<view class="chat-panel">
					<!-- 标题与操作 -->
					<view class="chat-header">
						<view class="chat-title-section">
							<text class="chat-title">{{ chatTitle }}</text>
							<text v-if="isTyping" class="typing-indicator">正在输入...</text>
						</view>
						<view class="chat-actions">
					<button class="text-btn" @click="renameChat">
						<image src="/static/name.png" class="menu-icon-small" />
						重命名
					</button>
					<button class="text-btn" @click="newChat">
						<image src="/static/chat-new.png" class="menu-icon-small" />
						新建对话
					</button>
				</view>
					</view>

					<!-- 消息列表 -->
					<scroll-view class="message-list" :scroll-top="scrollTop" scroll-y :scroll-into-view="scrollToMessage" ref="messageList">
							<!-- 欢迎消息 -->
							<view v-if="messages.length === 0" class="welcome-message">
								<image src="/static/touxiang_ai.webp" class="welcome-avatar" />
								<text class="welcome-text">您好！我是您的安全助手。请问您想了解哪方面的网络安全知识？</text>
							</view>
						
						<!-- 普通消息 -->
						<view class="message-row" v-for="(message, index) in messages" :key="index" :class="{ left: message.sender === 'system', right: message.sender === 'user' }">
							<!-- 系统消息头像 -->
							<view v-if="message.sender === 'system'" class="message-avatar">
								<image src="/static/touxiang_ai.webp" class="avatar-small" />
							</view>
							
							<view class="bubble-container">
								<view class="bubble" :class="message.sender">
										<!-- <rich-text :nodes="formatMessageContent(message.content)"></rich-text> -->
										<zeromarkdownview :markdown="message.content"></zeromarkdownview>
									<view v-if="message.sources && message.sources.length > 0" class="sources">
										<view class="source-title">引用来源</view>
										<view class="source-item" v-for="(source, sourceIndex) in message.sources" :key="sourceIndex">
											{{ source }}
										</view>
									</view>
									<view v-if="message.sender === 'system'" class="feedback">
									<text class="thumb" @click="feedbackMessage(index, 'like')">👍</text>
									<text class="thumb" @click="feedbackMessage(index, 'dislike')">👎</text>
								</view>
								</view>
								<text class="message-time">{{ message.time || formatCurrentTime() }}</text>
							</view>
							
							<!-- 用户消息头像 -->
							<view v-if="message.sender === 'user'" class="message-avatar">
								<image :src="currentAvatar" class="avatar-small" />
							</view>
						</view>
					</scroll-view>

						<!-- 输入区 -->
					<view class="input-bar">
						<textarea class="msg-input" auto-height placeholder="输入你的问题..." v-model="inputMessage" :disabled="isLoading" @keypress.enter="handleEnterKey" />
						<button class="send-btn" @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
					<image src="/static/send.png" class="send-icon" />
				</button>
					</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { streamChat, getChatHistory } from '../../api/api.js';
	import zeromarkdownview from "@/uni_modules/zero-markdown-view/components/zero-markdown-view/zero-markdown-view.vue";
	export default {
		components: {
			zeromarkdownview
		},
		data() {
			return {
				msg: "请输入问题",
				showDropdown: false,
				showNotification: false,
				currentAvatar: uni.getStorageSync('userAvatar') || '/static/touxiang01.webp',
				user_name: '示例用户',
				user_role: '普通用户', // 用户角色，管理员或普通用户
				user_id: 1, // 默认用户ID，实际应从登录信息中获取
				subjectid: 0, // 当前主题ID，0表示新主题
				avatarList: [
					'/static/touxiang01.webp',
					'/static/touxiang02.webp',
					'/static/touxiang03.webp',
					'/static/touxiang04.webp',
					'/static/touxiang05.webp',
					'/static/touxiang06.webp'
				],
				messages: [
					{
						sender: 'system',
						content: '您好！我是您的安全助手。请问您想了解哪方面的网络安全知识？',
						sources: []
					}
				],
				inputMessage: '',
				isLoading: false,
				chatTitle: '网络安全入门咨询',
				isTyping: false,
				scrollTop:999999999,
			}
		},
	mounted() {
	// 页面加载时初始化用户名
	this.initUserInfo();
	// 检查是否有继续对话的上下文
	this.checkContinueChat();
	// 自动获取当前会话ID
	this.loadCurrentSubjectId();
	
	// 监听本地存储变化，实时更新头像
	uni.$on('avatarChanged', (avatar) => {
		this.currentAvatar = avatar;
	});
},
	onShow() {
		// 页面显示时重新加载用户信息，确保头像同步
		this.initUserInfo();
	},
	methods: {
		// 加载当前会话ID
		loadCurrentSubjectId() {
			// 从本地存储获取当前会话ID
			const currentSubjectId = this.subjectid;
			if (currentSubjectId && currentSubjectId !== 0) {
				this.subjectid = currentSubjectId;
				console.log('已加载当前会话ID:', currentSubjectId);
			}
		},
		// 检查是否有继续对话的上下文
		checkContinueChat() {
			const continueSubject = uni.getStorageSync('currentSubject');
			if (continueSubject && continueSubject.subject_id) {
				// 设置主题ID
				this.subjectid = continueSubject.subject_id;
				// 加载历史对话内容
				this.loadChatHistory(continueSubject.subject_id);
				// 清除继续对话标记
				uni.removeStorageSync('currentSubject');
			}
		},
		// 加载聊天历史
		async loadChatHistory(subjectId) {
			try {
				const response = await getChatHistory(this.user_id, subjectId);
				if (response.success && response.chat_history) {
					// 清空当前消息
					this.messages = [];
					// 添加历史消息
					response.chat_history.forEach(content => {
						// 添加用户消息
						if (content.question) {
							this.messages.push({
								sender: 'user',
								content: content.question,
								time: this.formatTime(content.created_at)
							});
						}
						// 添加系统回复
						if (content.answer) {
							this.messages.push({
								sender: 'system',
								content: content.answer,
								time: this.formatTime(content.created_at)
							});
						}
					});
					// 滚动到底部
					this.$nextTick(() => {
						this.forceScrollToBottom();
					});
				}
			} catch (error) {
				console.error('加载聊天历史失败:', error);
				uni.showToast({
					title: '加载历史对话失败',
					icon: 'none',
					duration: 3000
				});
			}
		},
		// 格式化时间
		formatTime(timestamp) {
			try {
				const date = new Date(timestamp);
				if (isNaN(date.getTime())) {
					return '--:--';
				}
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			} catch (error) {
				console.error('时间格式化错误:', error);
				return '--:--';
			}
		},
		toggleDropdown() {
			this.showDropdown = !this.showDropdown;
		},
		closeDropdown() {
			this.showDropdown = false
		},
		initUserInfo() {
		// 从本地存储获取用户信息
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo && userInfo.user) {
			this.user_name = userInfo.user.user_name;
			// 根据用户ID判断角色，id为0的是管理员
			this.user_role = userInfo.user.user_id === 0 ? '管理员' : '普通用户';
		}
		// 从本地存储获取currentUser信息
		const currentUser = uni.getStorageSync('currentUser');
			if (currentUser) {
				this.user_id = currentUser.user_id;
			}
		// 从本地存储获取头像信息
		const savedAvatar = uni.getStorageSync('userAvatar');
		if (savedAvatar) {
			this.currentAvatar = savedAvatar;
		}
		},
		// 处理页面点击
			handlePageTap(e) {
				// 如果下拉菜单显示中，点击页面任何地方都关闭它
				if (this.showDropdown) {
					this.showDropdown = false;
				}
			},
			closeDropdown() {
				this.showDropdown = false;
			},
			selectAvatar(avatar) {
				this.currentAvatar = avatar;
				// 保存头像到本地存储，以便其他页面同步
				uni.setStorageSync('userAvatar', avatar);
				// 触发全局事件，通知其他页面更新头像
				uni.$emit('avatarChanged', avatar);
				uni.showToast({
					title: '头像已更新',
					icon: 'success'
				});
			},
			navigateTo(page) {
				uni.navigateTo({
					url: `/pages/${page}/${page}`
				})
			},
			logout() {
				uni.showModal({
					title: '确认退出',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除本地存储的用户信息
							uni.removeStorageSync('userInfo');
							uni.removeStorageSync('currentUser');
							// 跳转到登录页面
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}
					}
				});
			},
			toggleNotification() {
				this.showNotification = !this.showNotification;
				if (this.showNotification) {
					uni.showToast({
						title: '暂无新消息',
						icon: 'none',
						duration: 2000
					});
				}
			},
			// 清空所有消息
			clearAllMessages() {
				uni.showModal({
					title: '确认清空',
					content: '确定要清空所有消息吗？',
					success: (res) => {
						if (res.confirm) {
							this.messages = [];
						}
					}
				});
			},
			// 发送消息
		sendMessage() {
			if (this.inputMessage.trim() && !this.isLoading) {
				const userMessage = this.inputMessage.trim();
				// 添加用户消息
				this.messages.push({
					sender: 'user',
					content: userMessage,
					sources: [],
					time: this.formatCurrentTime()
				});
				// 清空输入框
				this.inputMessage = '';
				// 设置加载状态
				this.isLoading = true;
				this.isTyping = true;
				
				// 立即滚动到底部，显示用户消息
				this.$nextTick(() => {
					this.forceScrollToBottom();
				});
				
				// 添加"正在输入"消息
					const typingMessageIndex = this.messages.length;
					this.messages.push({
						sender: 'system',
						content: '', // 初始为空，流式显示内容
						sources: [],
						isTyping: true
					});
				
				try {
					// 调用流式聊天API，确保传递当前主题ID
				streamChat(
					this.user_id, 
					userMessage, 
					this.subjectid, // 自动获取当前会话ID
					// 接收增量消息的回调
					(chunk, fullContent, newSubjectId) => {
						// 首次收到回复时，更新主题ID（如果是新主题）
						if (newSubjectId && this.subjectid === 0) {
							this.subjectid = newSubjectId;
							// 保存当前会话ID到本地存储，用于多轮对话记忆
							uni.setStorageSync('currentSubjectId', newSubjectId);
						}
						// 更新系统回复消息（流式显示）
					if (this.messages[typingMessageIndex] && this.messages[typingMessageIndex].isTyping) {
						// 实时更新消息内容，实现一个字一个字显示
						this.messages[typingMessageIndex].content = fullContent;
						// 滚动到底部
						this.forceScrollToBottom();
					}
					},
					// 完成回调
					(fullContent, newSubjectId) => {
						// 处理完成后的逻辑
						if (newSubjectId && this.subjectid === 0) {
							this.subjectid = newSubjectId;
							// 保存当前会话ID到本地存储，用于多轮对话记忆
							uni.setStorageSync('currentSubjectId', newSubjectId);
						}
						// 移除正在输入状态
						if (this.messages[typingMessageIndex] && this.messages[typingMessageIndex].isTyping) {
							this.messages[typingMessageIndex].isTyping = false;
							// 添加时间戳
							this.messages[typingMessageIndex].time = this.formatCurrentTime();
						}
						this.isLoading = false;
						this.isTyping = false;
						// 确保最终滚动到底部
						this.$nextTick(() => {
							this.forceScrollToBottom();
						});
					}
				).catch(error => {
						console.error('发送消息失败:', error);
						// 更新错误消息
						if (this.messages[typingMessageIndex] && this.messages[typingMessageIndex].isTyping) {
							this.messages[typingMessageIndex] = {
								sender: 'system',
								content: `抱歉，发送消息失败：${error.message}`,
								sources: [],
								time: this.formatCurrentTime()
							};
						}
						this.isLoading = false;
						this.isTyping = false;
						// 显示错误提示
						uni.showToast({
							title: error.message || '发送消息失败，请稍后重试',
							icon: 'none',
							duration: 3000
						});
					});
				} catch (error) {
					console.error('发送消息时出错:', error);
					this.isLoading = false;
					this.isTyping = false;
					// 显示错误提示
					uni.showToast({
						title: '发送消息失败，请稍后重试',
						icon: 'none',
						duration: 3000
					});
				}
			}
		},
		// 格式化当前时间
		formatCurrentTime() {
			const now = new Date();
			const hours = now.getHours().toString().padStart(2, '0');
			const minutes = now.getMinutes().toString().padStart(2, '0');
			return `${hours}:${minutes}`;
		},
		// 重命名对话
		async renameChat() {
		  uni.showModal({
		    title: '重命名对话',
		    content: '',
		    editable: true,
		    placeholderText: this.chatTitle,
		    success: async (res) => {
		      if (res.confirm && res.content.trim()) {
		        const newTitle = res.content.trim();
		        const subjectId = this.subjectid; // 当前对话的主题 ID
		
		        if (!subjectId || subjectId <= 0) {
		          uni.showToast({
		            title: '无效的主题ID',
		            icon: 'none',
		            duration: 2000
		          });
		          return;
		        }
		
		        try {
		          // 显示加载中
		          uni.showLoading({ title: '正在保存...' });
		
		          // 调用后端接口
		          const response = await uni.request({
		            url: 'http://localhost:8000/subject_change', 
		            method: 'GET',
		            data: {
		              subject_id: subjectId,
		              new_subject: newTitle
		            },
		            
		          });
				  console.log("返回信息",response);
		
		          
		          uni.hideLoading();
		
		          if (!response.data.success) {
		            throw new Error('网络请求失败');
		          }
		
		
		          if (response.data.success) {
		            // 更新本地标题
		            this.chatTitle = newTitle;
		            // 可选：更新聊天列表缓存
		            // this.updateChatListCache(subjectId, newTitle);
		
		            uni.showToast({
		              title: '对话已重命名',
		              icon: 'success',
		              duration: 2000
		            });
		          } else {
		            uni.showToast({
		              title: response.data.message || '重命名失败',
		              icon: 'none',
		              duration: 2000
		            });
		          }
		        } catch (err) {
		          uni.hideLoading();
		          uni.showToast({
		            title: err.message || '操作失败',
		            icon: 'none',
		            duration: 2000
		          });
		        }
		      }
		    }
		  });
		},
		// 新建对话
		newChat() {
			uni.showModal({
				title: '新建对话',
				content: '确定要开始新的对话吗？当前对话内容将被保存。',
				success: (res) => {
					if (res.confirm) {
						this.messages = [];
						this.subjectid = 0;
						this.chatTitle = '网络安全入门咨询';
						this.inputMessage = '';
						this.scrollToBottom();
					}
				}
			});
		},
		// 处理回车键发送消息
		handleEnterKey(e) {
			// 如果按下Shift+Enter，不发送消息（用于换行）
			if (!e.shiftKey) {
				e.preventDefault();
				this.sendMessage();
			}
		},
		// 插入常见问题
		insertCommonQuestion(question) {
			this.inputMessage = question;
			// 滚动到输入框
			uni.createSelectorQuery().in(this).select('.msg-input').boundingClientRect((rect) => {
				if (rect) {
					uni.pageScrollTo({
						scrollTop: rect.top + 1000,
						duration: 300
					});
				}
			}).exec();
		},
		// 消息反馈
		feedbackMessage(messageIndex, type) {
			uni.showToast({
				title: type === 'like' ? '感谢您的反馈！' : '我们会努力改进！',
				icon: 'none',
				duration: 2000
			});
			// 这里可以添加反馈到服务器的逻辑
		},
		// 滚动到底部
		scrollToBottom() {
			// 使用ref直接操作scroll-view，比选择器更可靠
			this.scrollTop = 99999999999;
			// 强制触发滚动更新
			this.$nextTick(() => {
				this.scrollTop = this.scrollTop+5000;
			});
			// 使用scroll-view的API直接滚动到最底部
			this.$nextTick(() => {
				uni.createSelectorQuery().in(this).select('.message-list').boundingClientRect((rect) => {
					if (rect) {
						// 直接设置scrollTop为scroll-view的内容高度
						this.scrollTop = rect.height + 6000;
					}
				}).exec();
			});
		},
		// 强制滚动到底部（确保在任何情况下都能滚动）
		forceScrollToBottom() {
			// 连续调用多次，确保在复杂场景下也能滚动到底部
			this.scrollToBottom();
			// 延迟再次滚动，处理异步渲染情况
			setTimeout(() => {
				this.scrollToBottom();
			}, 50);
			// 再次延迟滚动，确保动画和渲染完成
			setTimeout(() => {
				this.scrollToBottom();
			}, 100);
		},
		// 格式化消息内容，支持Markdown
		formatMessageContent(content) {
			if (!content) return '';
			
			// 基本的Markdown转换
			let formatted = content
				// 代码块
				.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>')
				// 行内代码
				.replace(/`([^`]+)`/g, '<code>$1</code>')
				// 粗体
				.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
				.replace(/__([^_]+)__/g, '<strong>$1</strong>')
				// 斜体
				.replace(/\*([^*]+)\*/g, '<em>$1</em>')
				.replace(/_([^_]+)_/g, '<em>$1</em>')
				// 标题
				.replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
				.replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
				.replace(/^#\s+(.+)$/gm, '<h1>$1</h1>')
				// 无序列表
				.replace(/^\s*[-*+]\s+(.+)$/gm, '<li>$1</li>')
				// 有序列表
				.replace(/^\s*\d+\.\s+(.+)$/gm, '<li>$1</li>')
				// 链接
				.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
				// 换行
				.replace(/\n/g, '<br/>');
			
			// 处理列表
			if (formatted.includes('<li>')) {
				formatted = formatted.replace(/(<li>.*<\/li>)+/g, '<ul>$&</ul>');
			}
			
			return formatted;
		}
		}
	}
	</script>

<style>
	/* 布局 */
	.app-layout {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f6fa;
	}
	.topbar {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		background: #ffffff;
		box-shadow: 0 6rpx 20rpx rgba(0,0,0,0.06);
	}
	.topbar-left { display: flex; align-items: center; }
	.logo { width: 56rpx; height: 56rpx; border-radius: 12rpx; margin-right: 14rpx; }
	.brand { font-weight: 700; color: #333; font-size: 30rpx; }
	.topbar-center .page-title { font-size: 32rpx; color: #333; }
	.topbar-right { display: flex; align-items: center; }
	.icon { width: 44rpx; height: 44rpx; margin-right: 20rpx; opacity: .85; }
	.logout-btn { background: #e74c3c; color: #fff; border: none; border-radius: 8rpx; padding: 8rpx 16rpx; font-size: 24rpx; margin-right: 20rpx; cursor: pointer; transition: all 0.3s ease; display: flex; align-items: center; gap: 8rpx; }
	.logout-btn:hover { background: #c0392b; transform: scale(1.05); }
	.logout-icon { width: 24rpx; height: 24rpx; }
	.avatar { width: 44rpx; height: 44rpx; border-radius: 50%; background: #667eea; color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; }
	.avatar.lg { width: 72rpx; height: 72rpx; font-size: 32rpx; }

	.content { flex: 1; display: flex; padding: 24rpx; gap: 24rpx; }
	.user-box { display: flex; align-items: center; margin-bottom: 24rpx; }
	.user-meta { margin-left: 16rpx; }
	.user-name { font-size: 28rpx; color: #333; font-weight: 700; }
	.user-role { font-size: 22rpx; color: #888; }
	.menu { margin-top: 12rpx; }
	.menu-item { padding: 22rpx; border-radius: 12rpx; color: #444; }
	.menu-item.active { background: #eef1ff; color: #4f5bd5; font-weight: 700; }
	.menu-item + .menu-item { margin-top: 8rpx; }

	.main { flex: 1; }
	.main-inner { display: flex; gap: 24rpx; height: calc(100vh - 100rpx - 48rpx); }

	.chat-panel { flex: 1; background: #fff; border-radius: 16rpx; padding: 20rpx; box-shadow: 0 6rpx 20rpx rgba(0,0,0,0.06); display: flex; flex-direction: column; }
	.chat-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 16rpx; border-bottom: 2rpx solid #f0f0f0; }
	.chat-title-section { display: flex; align-items: center; gap: 12rpx; }
	.chat-title { font-size: 30rpx; font-weight: 700; color: #333; }
	.typing-indicator {
		font-size: 22rpx;
		color: #666;
		display: flex;
		align-items: center;
		gap: 6rpx;
	}
	.typing-indicator::after {
		content: '';
		display: inline-block;
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #666;
		animation: typing 1.4s infinite ease-in-out;
	}
	.typing-indicator::before {
		content: '';
		display: inline-block;
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #666;
		animation: typing 1.4s infinite ease-in-out 0.2s;
	}
	.typing-indicator span::before {
		content: '';
		display: inline-block;
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #666;
		animation: typing 1.4s infinite ease-in-out 0.4s;
	}
	@keyframes typing {
		0%, 60%, 100% {
			opacity: 0.3;
			scale: 0.8;
		}
		30% {
			opacity: 1;
			scale: 1.1;
		}
	}
	.text-btn { height: 64rpx; line-height: 64rpx; padding: 0 24rpx; background: #f1f3f5; color: #333; border-radius: 12rpx; border: none; margin-left: 12rpx; display: flex; align-items: center; gap: 10rpx; }
	.menu-icon-small { width: 28rpx; height: 28rpx; }
	.text-btn.danger { background: #ffe8e8; color: #d64545; }

	.message-list { flex: 1; padding: 20rpx 10rpx; overflow-y: auto; }
	.message-row { display: flex; margin-bottom: 24rpx; position: relative; align-items: flex-start; }
	.message-row.left { justify-content: flex-start; }
	.message-row.right { justify-content: flex-end; }
	
	/* 消息头像 */
	.message-avatar {
		width: 56rpx;
		height: 56rpx;
		margin: 0 12rpx;
		display: flex;
		align-items: flex-start;
	}
	.avatar-small {
		width: 56rpx;
		height: 56rpx;
		border-radius: 50%;
		object-fit: cover;
	}
	
	/* 消息气泡容器 */
	.bubble-container {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		max-width: 70%;
	}
	.message-row.right .bubble-container {
		align-items: flex-end;
	}
	
	/* Markdown样式 */
	.bubble h1,
	.bubble h2,
	.bubble h3,
	.bubble h4,
	.bubble h5,
	.bubble h6 {
		margin: 10rpx 0;
		font-weight: bold;
		line-height: 1.3;
	}
	
	.bubble h1 { font-size: 36rpx; color: #333; }
	.bubble h2 { font-size: 32rpx; color: #444; }
	.bubble h3 { font-size: 28rpx; color: #555; }
	
	.bubble strong {
		font-weight: bold;
		color: #333;
	}
	
	.bubble em {
		font-style: italic;
		color: #666;
	}
	
	.bubble code {
		background: #f5f5f5;
		padding: 4rpx 8rpx;
		border-radius: 4rpx;
		font-family: 'Courier New', monospace;
		font-size: 24rpx;
		color: #e74c3c;
	}
	
	.bubble pre {
		background: #2d2d2d;
		color: #f8f8f2;
		padding: 20rpx;
		border-radius: 8rpx;
		margin: 10rpx 0;
		overflow-x: auto;
	}
	
	.bubble pre code {
		background: none;
		padding: 0;
		color: inherit;
		font-size: 24rpx;
		line-height: 1.5;
	}
	
	.bubble ul,
	.bubble ol {
		margin: 10rpx 0;
		padding-left: 40rpx;
	}
	
	.bubble li {
		margin: 8rpx 0;
		line-height: 1.4;
	}
	
	.bubble a {
		color: #3498db;
		text-decoration: none;
	}
	
	.bubble a:hover {
		text-decoration: underline;
	}
	
	/* 消息气泡 */
	.bubble {
		max-width: 100%;
		padding: 22rpx 26rpx;
		border-radius: 18rpx;
		box-shadow: 0 4rpx 14rpx rgba(0,0,0,0.04);
		transition: all 0.2s ease;
		position: relative;
		word-wrap: break-word;
	}

	.bubble.system {
		background: #f5f6fa;
		color: #333;
		border-top-left-radius: 6rpx;
	}
	.bubble.user {
		background: #4f5bd5;
		color: #fff;
		border-top-right-radius: 6rpx;
	}
	
	/* 消息时间 */
	.message-time {
		font-size: 20rpx;
		color: #999;
		margin-top: 6rpx;
		margin-left: 10rpx;
		margin-right: 10rpx;
	}
	.message-row.right .message-time {
		margin-left: 0;
		margin-right: 10rpx;
	}
	
	/* 引用来源 */
	.sources {
		margin-top: 14rpx;
		padding-top: 12rpx;
		border-top: 2rpx solid #eaeaea;
	}
	.bubble.user .sources {
		border-top-color: rgba(255, 255, 255, 0.2);
	}
	.source-title { font-size: 22rpx; color: #666; margin-bottom: 8rpx; }
	.bubble.user .source-title { color: rgba(255, 255, 255, 0.8); }
	.source-item { font-size: 22rpx; color: #888; }
	.bubble.user .source-item { color: rgba(255, 255, 255, 0.6); }
	
	/* 反馈按钮 */
	.feedback {
		margin-top: 12rpx;
		display: flex;
		gap: 20rpx;
	}
	.thumb {
		font-size: 26rpx;
		opacity: .8;
		cursor: pointer;
		transition: all 0.2s ease;
	}
	.thumb:hover {
		opacity: 1;
		transform: scale(1.1);
	}
	

	
	/* 欢迎消息 */
	.welcome-message {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 60rpx;
		text-align: center;
		color: #666;
		max-width: 80%;
		margin: 0 auto;
	}
	.welcome-avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		margin-bottom: 24rpx;
		box-shadow: 0 0 24rpx rgba(0, 0, 0, 0.12);
		animation: pulse 2s infinite;
	}
	@keyframes pulse {
		0% {
			box-shadow: 0 0 24rpx rgba(0, 0, 0, 0.12);
		}
		50% {
			box-shadow: 0 0 32rpx rgba(79, 91, 213, 0.2);
		}
		100% {
			box-shadow: 0 0 24rpx rgba(0, 0, 0, 0.12);
		}
	}
	.welcome-text {
		font-size: 30rpx;
		line-height: 1.7;
		color: #555;
		font-weight: 500;
	}
	
	/* 加载状态 */
	.bubble.loading {
		opacity: 0.7;
	}
	.bubble.loading .loading-dots {
		display: flex;
		gap: 4rpx;
	}
	.loading-dot {
		display: inline-block;
		width: 8rpx;
		height: 8rpx;
		border-radius: 50%;
		background-color: #666;
		animation: loading 1.4s infinite ease-in-out;
	}
	.loading-dot:nth-child(2) {
		animation-delay: 0.2s;
	}
	.loading-dot:nth-child(3) {
		animation-delay: 0.4s;
	}
	@keyframes loading {
		0%, 60%, 100% {
			opacity: 0.3;
			scale: 0.8;
		}
		30% {
			opacity: 1;
			scale: 1.1;
		}
	}

	/* 输入区域 */
	.input-bar { border-top: 2rpx solid #f0f0f0; padding: 16rpx 0; display: flex; gap: 16rpx; align-items: center; }
	.msg-input {
		flex: 1;
		min-height: 70rpx;
		max-height: 220rpx;
		padding: 20rpx 28rpx;
		outline: none;
		font-size: 28rpx;
		line-height: 40rpx;
		overflow-y: auto;
		color: #333;
		background: #fff;
		border-radius: 36rpx;
		box-shadow: 0 4rpx 14rpx rgba(0,0,0,0.04);
		transition: all 0.2s ease;
	}
	.msg-input:focus {
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
	}
	.msg-input::-webkit-scrollbar {
		width: 6rpx;
	}
	.msg-input::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 3rpx;
	}
	.msg-input::-webkit-scrollbar-thumb {
		background: #c1c1c1;
		border-radius: 3rpx;
	}
	.msg-input::-webkit-scrollbar-thumb:hover {
		background: #a8a8a8;
	}
	.send-btn {
		width: 96rpx;
		height: 96rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #3a86ff 0%, #3a0ca3 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 24rpx rgba(58, 134, 255, 0.5);
		transition: all 0.3s ease;
		color: white;
	}
	.send-btn:hover:not(:disabled) {
		background: linear-gradient(135deg, #2563eb 0%, #2a0a63 100%);
		transform: scale(1.08);
		box-shadow: 0 10rpx 28rpx rgba(58, 134, 255, 0.6);
	}
	.send-btn:active:not(:disabled) { 
		transform: scale(0.95); 
	}
	.send-btn:disabled { 
		background: #ccc; 
		box-shadow: none; 
		transform: none;
		color: #999;
	}
	.send-icon {
		width: 48rpx;
		height: 48rpx;
		filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
	}
	
	/* 常见问题快捷按钮 */
	.quick-questions {
		display: flex;
		flex-wrap: wrap;
		gap: 14rpx;
		padding: 18rpx 20rpx;
		max-height: 180rpx;
		overflow-y: auto;
	}
	.quick-question-btn {
		padding: 12rpx 26rpx;
		background: #f5f6fa;
		border: 2rpx solid #e8e9ed;
		border-radius: 42rpx;
		font-size: 26rpx;
		color: #666;
		transition: all 0.2s ease;
		white-space: nowrap;
		cursor: pointer;
	}
	.quick-question-btn:hover {
		background: #4f5bd5;
		border-color: #4f5bd5;
		color: #fff;
		transform: translateY(-2rpx);
		box-shadow: 0 4rpx 12rpx rgba(79, 91, 213, 0.2);
	}
	


	/* 下拉菜单 */
	.dropdown-menu {
		position: fixed;
		top: 100rpx;
		right: 30rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 12rpx 40rpx rgba(0,0,0,0.15);
		z-index: 1000;
		overflow: hidden;
	}
	.dropdown-content {
		width: 300rpx;
		background: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		box-shadow: 0 12rpx 40rpx rgba(0,0,0,0.15);
		border: 1rpx solid #eaeaea;
	}
	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 16rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	.dropdown-content .menu {
		margin-top: 0;
	}
	.dropdown-content .menu-item {
		padding: 20rpx 16rpx;
		border-radius: 8rpx;
		color: #444;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		transition: all 0.2s ease;
	}
	.dropdown-content .menu-item:hover {
		background: #f5f6fa;
		color: #4f5bd5;
	}
	.dropdown-content .menu-item.active { background: #eef1ff; color: #4f5bd5; font-weight: 700; }
	.dropdown-content .menu-item + .menu-item { margin-top: 4rpx; }
	.dropdown-content .logout-item { color: #e74c3c; }
	.dropdown-content .logout-item .logout-icon { width: 24rpx; height: 24rpx; margin-right: 16rpx; }
	.dropdown-content .menu-icon { width: 24rpx; height: 24rpx; margin-right: 8rpx; }

	/* 头像选择器 */
	.avatar-selector { margin-bottom: 24rpx; padding-bottom: 24rpx; border-bottom: 1rpx solid #f1f3f5; }
	.selector-title { display: block; font-size: 28rpx; color: #666; margin-bottom: 16rpx; }
	.avatar-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16rpx; }
	.avatar-option { width: 72rpx; height: 72rpx; border-radius: 50%; border: 2rpx solid transparent; cursor: pointer; transition: all 0.2s ease; }
	.avatar-option:hover {
		transform: scale(1.1);
	}
	.avatar-option.active { border-color: #4f5bd5; box-shadow: 0 0 0 2rpx rgba(79, 91, 213, 0.2); }

	/* 正在输入提示 */
	.typing-indicator {
		font-size: 22rpx;
		color: #666;
		display: flex;
		align-items: center;
		gap: 6rpx;
	}
	.typing-indicator::after {
		content: '';
		display: inline-block;
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #666;
		animation: typing 1.4s infinite ease-in-out;
	}
	.typing-indicator::before {
		content: '';
		display: inline-block;
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #666;
		animation: typing 1.4s infinite ease-in-out 0.2s;
	}
	.typing-indicator span::before {
		content: '';
		display: inline-block;
		width: 6rpx;
		height: 6rpx;
		border-radius: 50%;
		background-color: #666;
		animation: typing 1.4s infinite ease-in-out 0.4s;
	}
	@keyframes typing {
		0%, 60%, 100% {
			opacity: 0.3;
			scale: 0.8;
		}
		30% {
			opacity: 1;
			scale: 1.1;
		}
	}

	/* 动画效果 */
	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
	.message-row {
		animation: fadeIn 0.3s ease-out;
	}

	/* 滚动条样式优化 */
	.message-list::-webkit-scrollbar {
		width: 8rpx;
	}
	.message-list::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 4rpx;
	}
	.message-list::-webkit-scrollbar-thumb {
		background: #c1c1c1;
		border-radius: 4rpx;
	}
	.message-list::-webkit-scrollbar-thumb:hover {
		background: #a8a8a8;
	}

	/* 响应式布局 */
	@media screen and (max-width: 768px) {
		.main-inner { height: auto; }
		.message-list {
			padding: 10rpx 5rpx;
		}
		.quick-questions {
			max-height: 150rpx;
		}
		.bubble-container {
			max-width: 75%;
		}
		.send-btn {
			width: 88rpx;
			height: 88rpx;
		}
		.msg-input {
			min-height: 64rpx;
		}
	}
	
	/* 超小屏幕优化 */
	@media screen and (max-width: 375px) {
		.bubble-container {
			max-width: 80%;
		}
		.input-tools {
			gap: 12rpx;
		}
		.tool-btn {
			width: 64rpx;
			height: 64rpx;
		}
	}
</style>
